#!/usr/bin/env python
# encoding: utf-8
"""
@author: youfeng
@email: youfeng243@163.com
@license: Apache Licence
@file: mongo_export.py
@time: 2017/12/1 21:29
"""
import os

from logger import Logger
from mongo import MongDb

APP_DATA_CONF = {
    'host': '172.16.215.16',
    'port': 40042,
    'db': 'app_data',
    'username': 'work',
    'password': 'haizhi',
}

log = Logger('mongo_utime.log').get_logger()

# 配置文件文件夹
CONFIG_FOLDER_PATH = './table_list'


class PrintUtime(object):
    def __init__(self, config_folder_path):

        self.app_data_db = MongDb(APP_DATA_CONF['host'], APP_DATA_CONF['port'], APP_DATA_CONF['db'],
                                  APP_DATA_CONF['username'], APP_DATA_CONF['password'], log=log)
        self.config_folder_path = config_folder_path

        # 获得配置文件列表
        self.file_list = self.get_file_list(config_folder_path)

        self.print_process(self.file_list)

    @staticmethod
    def get_file_list(file_path):
        file_list = []
        if not os.path.isdir(file_path):
            log.error("文件路径不存在: {}".format(file_path))
            return file_list

        return os.listdir(file_path)

    @staticmethod
    def parse_table_name(file_name):
        return file_name.split('.')[0]

    @staticmethod
    def get_company_list(config_file_path):
        company_list = []
        with open(config_file_path, 'r') as p_file:
            for line in p_file:
                company = line.strip().strip('\n').strip('\r')
                company_list.append(company)

        log.info("当前配置文件企业数目: company num = {} config = {}".format(len(company_list), config_file_path))
        return company_list

    def print_by_config(self, file_name):
        table_name = self.parse_table_name(file_name)
        config_file_path = self.config_folder_path + '/' + file_name
        log.info("需要导出的数据表: {}".format(table_name))
        log.info("企业名单配置文件路径: {}".format(config_file_path))

        # 获得企业名单
        company_list = self.get_company_list(config_file_path)

        for company in company_list:
            item = self.app_data_db.find_one(table_name, {'company': company}, ['_utime'])
            _utime = item.get('_utime')
            log.info("当前企业更新时间: _utime:{} {}".format(_utime, company))

    def print_process(self, file_list):
        for file_name in file_list:
            self.print_by_config(file_name)


def main():
    PrintUtime(CONFIG_FOLDER_PATH)


if __name__ == '__main__':
    main()
